'''
Created on Feb 4, 2015

@author: dewey
'''

units = {}
category = {}
category_all = {}
categories = ["ratio", "distance", "area", "mass", "density", "velocity", "accumulation_rate", "time"]

units[""] = 1
units["unitless"] = 1
units["percent"] = .01
units["%"] = .01
units["permille"] = .001
units["\u2030"] = .001
units["ppt"] = .001
units["ppm"] = 1e-6
units["ppb"] = 1e-9
units["ppt"] = 1e-12
category["ratio"] = ["unitless", "percent", "permille", "ppm", "ppb", "ppt"]
category_all["ratio"] = [None, "", "unitless", "percent", "%", "ppt", "\u2030", "permille", "ppm", "ppb", "ppt"]

units["km"] = 1000
units["m"] = 1
units["cm"] = .01
units["mm"] = .001
units["um"] = 1e-6
category["distance"] = ["m", "cm", "mm", "um"]
category_all["distance"] = ["km", "m", "cm", "mm", "um"]

units["km2"] = 1e6
units["m2"] = 1
units["cm2"] = 1e-4
units["mm2"] = 1e-9
category["area"] = ["m2", "cm2", "mm2"]
category_all["area"] = ["km2", "m2", "cm2", "mm2"]

units["km3"] = 1e12
units["m3"] = 1
units["cm3"] = 1e-6
units["mm3"] = 1e-12
category["volume"] = ["m3", "cm3", "mm3"]
category_all["volume"] = ["km3", "m3", "cm3", "mm3"]

units["kg"] = 1
units["g"] = .001
units["mg"] = 1e-6
units["ug"] = 1e-9
category["mass"] = ["kg", "g", "mg", "ug"]
category_all["mass"] = ["kg", "g", "mg", "ug"]

units["kg/m3"] = 1
units["g/mL"] = 1000
units["g/cm3"] = 1000
category["density"] = ["g/cm3", "kg/m3"]
category_all["density"] =  ["kg/m3", "g/cm3", "g/mL"]

units["m/yr"] = 1
units["cm/yr"] = .01
units["mm/yr"] = .001
category["velocity"] = ["m/yr", "cm/yr", "mm/yr"]
category_all["velocity"] = ["m/yr", "cm/yr", "mm/yr"]

units["kg/m2/yr"] = 1
units["g/m2/yr"] = .001
units["mg/m2/yr"] = 1e-6
units["g/cm2/yr"] = 10
units["mg/cm2/yr"] = 1e-2
units["ug/cm2/yr"] = 1e-5
category["accumulation_rate"] = ["kg/m2/yr", "g/m2/yr", "mg/m2/yr", "g/cm2/yr", "mg/cm2/yr", "ug/cm2/yr"]
category_all["accumulation_rate"] = ["kg/m2/yr", "g/m2/yr", "mg/m2/yr", "g/cm2/yr", "mg/cm2/yr", "ug/cm2/yr"]

units["yr"] = 1
units["century"] = 100
units["millenium"] = 1000
units["ka"] = 1000
units["Ma"] = 1e6
units["Ga"] = 1e9
category["time"] = ["yr", "ka", "Ma"]
category_all["time"] = ["yr", "century", "millenium", "ka", "Ma", "Ga", "Year_AD", "Cal_Years_BP", "Cal_Years_Pre_1950", "14C_Years"]

def to_SI(value, unit):
    return value * units[unit]

def from_SI(value, unit):
    return value / units[unit]

def convert(value, unit_from, unit_to):
    return from_SI(to_SI(value, unit_from), unit_to)

def get_category(target_unit):
    for category, values in category_all.items():
        for unit in values:
            if target_unit == unit:
                return category
    return None

def label(unit_id):
    if unit_id == "percent":
        return "%"
    elif unit_id == "permille":
        return "\u2030"
    elif unit_id is None:
        return ""
    else:
        return unit_id
    